/**@FILE:OperLogAdvice.java
 * @AUTHOR:qingsheng.zheng
 * @DATE:2014-12-8 上午9:58:27*/

package com.xf.toy.web.framework.annotation;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class OperLogAdvice implements MethodInterceptor {
	private Logger logger = LoggerFactory.getLogger(getClass());

	public Object invoke(MethodInvocation invocation) throws Throwable {
		String path = "";
		String remark = "";

		if (invocation.getMethod().isAnnotationPresent(Operlog.class)) {
			Class classType = invocation.getClass();
			Method method = invocation.getMethod();
			Object args[] = invocation.getArguments();

			Annotation annotation = invocation.getMethod().getAnnotation(
					Operlog.class);
			if (annotation != null) {
				path = ((Operlog) annotation).path();
				remark = ((Operlog) annotation).remark();
			}
			// LOG4J的统一日志记录
			loggerInfo(classType, method, args);
			return invocation.proceed();

		} else {
			return invocation.proceed();
		}

	}

	public void loggerInfo(Class classType, Method method, Object args[]) {
		HttpServletRequest request = null;
		HttpServletResponse response = null;
		StringBuffer arginfo = new StringBuffer("");
		StringBuffer loginfo = new StringBuffer("");
		arginfo.append("Params:");
		for (int i = 0; i < args.length; i++) {
			Object o = args[i];
			if (o instanceof HttpServletRequest) {
				request = (HttpServletRequest) o;
				continue;
			}
			if (o instanceof HttpServletResponse) {
				response = (HttpServletResponse) o;
				continue;
			}
			arginfo.append("|").append(o.toString()).append("|");
	

		}
		arginfo.append("\n");
		String methodinfo = "[" + method.getDeclaringClass().toString() + "(method:"
				+ method.getName() + ")]\n";
		String reqinfo = "[URI:" + request.getRequestURI() + "]\n";
		loginfo.append("\n=======================================>\n");
		loginfo.append(methodinfo).append(reqinfo).append(arginfo);
		loginfo.append("=======================================>\n");
		logger.info(loginfo.toString());
	}
}
